import axios from 'axios'
import { Toast } from 'vant'
import store from '../store'
import router from '@/router'
import { authorizationsput } from '../api/user'
const _axios = axios.create({
  baseURL: process.env.VUE_APP_URL
})
_axios.interceptors.request.use(
  config => {
    if (!config.noToken) {
      config.headers.Authorization = `Bearer ${store.getters['user/getToken']}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
_axios.interceptors.response.use(
  res => {
    return res.data
  },
  async error => {
    if (error.response.status === 401) {
      try {
        const restoken = await authorizationsput()
        console.log('refreshToken', restoken)
        store.commit('user/setToken', restoken.data.token)
        return _axios(error.config)
      } catch {
        if (
          !error.config.noError &&
          error.response.data &&
          error.response.data.message
        ) {
          Toast.fail(error.response.data.message)
        }
        store.commit('user/setToken', '')

        router.push('/login?redirect=' + router.currentRoute.fullPath)
      }
    } else {
      if (
        !error.config.noError &&
        error.response.data &&
        error.response.data.message
      ) {
        Toast.fail(error.response.data.message)
      }
    }
    // if (error.response.status === 401) {
    //   store.commit('user/')
    // }
    console.log('error', [error])
    return Promise.reject(error)
  }
)
export default _axios
